package model

import (
	"context"
	"errors"

	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20)" json:"username"`
	Password string `gorm:"type:varchar(50)" json:"password"`
	IdCode   string `gorm:"type:char(18)" json:"id_code"`
	RealName string `gorm:"type:varchar(10)" json:"real_name"`
	Power    int    `gorm:"type:tinyint;comment:0 普通用户，1 vip用户，2 管理员" json:"power"`
	Status   int    `gorm:"type:tinyint" json:"status"`
	Mobile   string `gorm:"type:char(11)" json:"mobile"`
}

const (
	ORDINARY = 0
	VIP      = 1
	ADMIN    = 2
)

// AddUser 添加或修改用户信息
func AddUser(user User) error {
	test := User{}
	DB.Where("mobile", user.Mobile).Find(&test)
	if test.ID == 0 {
		obj := User{}
		DB.Where("username", test.Username).Find(&obj)
		if obj.ID == 0 {
			DB.Create(&user)
		} else {
			return errors.New("用户名已存在，无法保存")
		}
	} else {
		obj := User{}
		DB.Where("username", test.Username).Find(&obj)
		if obj.ID == 0 {
			test.Power = user.Power
			test.Mobile = user.Mobile
			test.Username = user.Username
			DB.Save(&user)
		} else {
			return errors.New("用户名已存在，无法保存")
		}
	}
	return nil
}

// DelUser 删除用户信息
func DelUser(userId int) error {
	obj := User{}
	obj.ID = uint(userId)
	err := DB.Delete(&obj).Error
	if err != nil {
		return err
	}
	return nil
}

// GetMessage 获取用户信息
func GetMessage(userId int) User {
	obj := User{}
	DB.Where("id", userId).Find(&obj)
	return obj
}

// TestPower 验证用户权限
func TestPower(userId int) int {
	obj := User{}
	DB.Where("id", userId).Find(&obj)
	switch obj.Power {
	case 0:
		return ORDINARY
	case 1:
		return VIP
	case 2:
		return ADMIN
	}
	return -1
}

func TestCode(mobile string, code string) bool {
	obj := User{}
	DB.Where("mobile", mobile).Find(&obj)
	if obj.ID == 0 {
		return false
	}
	result, _ := St.Get(context.Background(), mobile).Result()
	if result == code {
		return true
	} else {
		return false
	}
}

func Login(username string, password string) uint {
	obj := User{}
	DB.Where("username", username).Find(&obj)
	if obj.Password == password {
		return 0
	}
	return obj.ID
}

func GetIdByMobile(mobile string) uint {
	obj := User{}
	DB.Where("mobile", mobile).Find(&obj)
	return obj.ID
}
